package com.pet.service.impl;

import com.pet.mapper.AdoptionApplicationMapper;
import com.pet.mapper.PetMapper;
import com.pet.pojo.AdoptionApplication;
import com.pet.service.AdoptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 领养服务实现类
 */
@Service
public class AdoptionServiceImpl implements AdoptionService {
    
    @Autowired
    private AdoptionApplicationMapper adoptionApplicationMapper;
    
    @Autowired
    private PetMapper petMapper;
    
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    @Override
    @Transactional
    public boolean submitApplication(AdoptionApplication application) {
        // 设置申请时间
        application.setApplyTime(LocalDateTime.now().format(formatter));
        
        // 设置初始状态为待审核
        application.setStatus(0);
        
        // 提交申请
        boolean result = adoptionApplicationMapper.insert(application) > 0;
        
        // 更新宠物状态为领养中
        if (result) {
            petMapper.updateStatus(application.getPetId(), 2);
        }
        
        return result;
    }
    
    @Override
    @Transactional
    public boolean reviewApplication(Long id, Integer status, String reviewRemark) {
        // 设置审核时间
        String reviewTime = LocalDateTime.now().format(formatter);
        
        // 更新申请状态
        boolean result = adoptionApplicationMapper.updateStatus(id, status, reviewRemark) > 0;
        
        if (result) {
            // 获取申请信息
            AdoptionApplication application = adoptionApplicationMapper.selectById(id);
            
            // 如果审核通过，更新宠物状态为已领养
            if (status == 1) {
                petMapper.updateStatus(application.getPetId(), 1);
            } 
            // 如果审核拒绝，更新宠物状态为待领养
            else if (status == 2) {
                petMapper.updateStatus(application.getPetId(), 0);
            }
        }
        
        return result;
    }
    
    @Override
    public AdoptionApplication getApplicationById(Long id) {
        return adoptionApplicationMapper.selectById(id);
    }
    
    @Override
    public List<AdoptionApplication> getApplicationsByPetId(Long petId) {
        return adoptionApplicationMapper.selectByPetId(petId);
    }
    
    @Override
    public List<AdoptionApplication> getApplicationsByPhone(String phone) {
        return adoptionApplicationMapper.selectByPhone(phone);
    }
    
    @Override
    public List<AdoptionApplication> getAllApplications() {
        return adoptionApplicationMapper.selectAll();
    }
} 